<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="拜访概要" prop="visitRecordName">
        <el-input
          v-model="queryParams.visitRecordName"
          placeholder="请输入拜访概要"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
     
      <el-form-item label="拜访时间" prop="visitRecordDate">
        <el-date-picker clearable size="small"
          v-model="queryParams.visitRecordDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择拜访时间">
        </el-date-picker>
      </el-form-item>
     
      
      
      <el-form-item label="拜访公司" prop="visitRecordCompanyName">
        <el-input
          v-model="queryParams.visitRecordCompanyName"
          placeholder="请输入拜访公司"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['crm:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="visitRecordId" />
      <el-table-column label="拜访概要" align="center" prop="visitRecordName" />
      <el-table-column label="时间" align="center" prop="visitRecordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitRecordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="visitRecordLinkmenNames" />
      <el-table-column label="业务员" align="center" prop="visitRecordUserNames" />
      <el-table-column label="部门" align="center" prop="visitRecordDeptName" />
      <el-table-column label="公司" align="center" prop="visitRecordCompanyName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:records:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:records:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拜访记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="拜访公司" prop="visitRecordCompanyName">
          <el-input v-model="form.visitRecordCompanyName" placeholder="请输入拜访公司" :disabled="true"/>
        </el-form-item>
        <el-form-item label="拜访概要" prop="visitRecordName">
          <el-input v-model="form.visitRecordName" placeholder="请输入拜访概要" />
        </el-form-item>
        <el-form-item label="详细信息" prop="visitRecordDesc">
          <el-input v-model="form.visitRecordDesc" placeholder="请输入详细信息" />
        </el-form-item>
        <el-form-item label="联系人" prop="visitRecordLinkmen" v-show="false">
          <el-input v-model="form.visitRecordLinkmen" placeholder="请输入联系人ids" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-select v-model="linkmanIds" ref="linkmenSelect" placeholder="请选择" style="width:100%" multiple>
            <el-option
              v-for="linkman in linkmen"
              :key="linkman.linkmanId"
              :label="linkman.linkmanName"
              :value="linkman.linkmanId">
            </el-option>
          </el-select>
        </el-form-item>
       
        <el-form-item label="拜访公司id" prop="visitRecordCompanyId" v-show="false">
          <el-input v-model="form.visitRecordCompanyId" placeholder="请输入拜访公司id" />
        </el-form-item>
       
        <el-form-item label="拜访目标" prop="visitObjectivesId" v-show="false">
          <el-input v-model="form.visitObjectivesId" placeholder="请输入拜访目标" />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="visitRecordLinkmenNames" v-show="false">
          <el-input v-model="form.visitRecordLinkmenNames" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="所属部门id" prop="visitRecordDeptId" v-show="false">
          <el-input v-model="form.visitRecordDeptId" placeholder="请输入所属部门id" />
        </el-form-item>
        <el-form-item label="所属部门" prop="visitRecordDeptName" v-show="false"> 
          <el-input v-model="form.visitRecordDeptName" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="所属部门" prop="visitRecordDeptId" >
           <treeselect v-model="form.visitRecordDeptId" ref="deptTree"  :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-select v-model="userids" ref="userSelect" placeholder="请选择" style="width:100%" multiple>
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务员" prop="visitRecordUserNames" v-show="false">
          <el-input v-model="form.visitRecordUserNames" placeholder="请输入业务员姓名" />
        </el-form-item>
         <el-form-item label="业务ids" prop="visitRecordUsers" v-show="false">
          <el-input v-model="form.visitRecordUsers" placeholder="请输入业务人员ids" />
        </el-form-item>
        <el-form-item label="拜访时间" prop="visitRecordDate">
          <el-date-picker clearable size="small"
            v-model="form.visitRecordDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择拜访时间"
            style="width:100%">
          </el-date-picker>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords, exportRecords } from "@/api/crm/records";
import { getObjectives } from "@/api/crm/objectives";
import { getlinkmen } from "@/api/crm/linkman";
import { getusers,selectUserById } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect,getDeptTreeName } from "@/api/system/dept";
export default {
  name: "Records",
  components: { Treeselect },
  data() {
    return {

      //是否第一次加载更新userids
      isFirst: false,
      //拜访目标对象 
      objective: undefined,
      //联系人
      linkmen: [],
      //暂存联系人ids
      linkmanIds: [],
      //暂存联系人名称
      linkmanNames: [],
      //部门树
      deptOptions: [],
      //部门员工，业务员
      users: [],
      //暂存业务员ids
      userids: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拜访记录表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        visitRecordName: null,
        visitRecordDesc: null,
        visitRecordLinkmen: null,
        visitRecordUsers: null,
        visitRecordCompanyId: null,
        visitRecordDate: null,
        visitObjectivesId: null,
        visitRecordLinkmenNames: null,
        visitRecordUserNames: null,
        visitRecordDeptId: null,
        visitRecordDeptName: null,
        visitRecordCompanyName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    //从路由中获得拜访目标id，并得到拜访目标对象
    getObjectives(this.$route.params.visitObjectivesId).then(res => {
      this.objective = res.data;
      this.queryParams.visitObjectivesId = this.objective.visitObjectivesId;
    });

    this.getList();
  },
  methods: {
    /** 查询拜访记录列表 */
    getList() {
      this.loading = true;
      //this.queryParams.visitObjectivesId = this.objective.visitObjectivesId;
      listRecords(this.queryParams).then(response => {
        this.recordsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        visitRecordId: null,
        visitRecordName: null,
        visitRecordDesc: null,
        visitRecordLinkmen: '',
        visitRecordUsers: null,
        visitRecordCompanyId: this.objective.visitObjectivesCompanyId,
        visitRecordDate: null,
        visitObjectivesId: this.objective.visitObjectivesId,
        visitRecordLinkmenNames: '',
        visitRecordUserNames: null,
        visitRecordDeptId: null,
        visitRecordDeptName: null,
        visitRecordCompanyName: this.objective.visitObjectivesCompanyName
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.visitRecordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //获取联系人
      getlinkmen({companyId:this.objective.visitObjectivesCompanyId}).then(res=>{
        this.linkmen = res.data;
      });

      //获取部门树
      this.getTreeselect();
      this.open = true;
      this.title = "添加拜访记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isFirst = true;
      //获取联系人并选中
      //获取联系人
      getlinkmen({companyId:this.objective.visitObjectivesCompanyId}).then(res=>{
        this.linkmen = res.data;
      });
      //获取部门树
      this.getTreeselect();
      const visitRecordId = row.visitRecordId || this.ids
      getRecords(visitRecordId).then(response => {
        this.form = response.data;
        this.linkmanIds = this.form.visitRecordLinkmen.split(',').map(Number);
        
        
        this.open = true;
        this.title = "修改拜访记录";
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //获取联系人的id和姓名
          const lobjs = this.getSelectedObjs(this.$refs.linkmenSelect.selected);
          this.form.visitRecordLinkmen = lobjs.oids;
          this.form.visitRecordLinkmenNames = lobjs.onames;

          //获取业务员的id和姓名
          const uobjs = this.getSelectedObjs(this.$refs.userSelect.selected);
          this.form.visitRecordUsers = uobjs.oids;
          this.form.visitRecordUserNames = uobjs.onames;

          if (this.form.visitRecordId != null) {
            updateRecords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 获取下拉菜单中的数据 */
    getSelectedObjs(objs){
          let lids = '';//临时ids
          let lnames = '';//临时names
          objs.forEach(obj=>{
            lids += obj.value + ',';
            lnames += obj.label + ',';
          });
          lids = lids.substring(0, lids.lastIndexOf(','));
          lnames = lnames.substring(0, lnames.lastIndexOf(','));
          return {oids: lids,onames:lnames};
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const visitRecordIds = row.visitRecordId || this.ids;
      this.$modal.confirm('是否确认删除拜访记录编号为"' + visitRecordIds + '"的数据项？').then(function() {
        return delRecords(visitRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //选中部门后级联员工菜单
    onDeptChange(v){
      //设置部门名称
      
        this.form.visitRecordDeptName = getDeptTreeName(this.deptOptions,v);
      
      
      //清空数据数组
      this.users = [];
      //清空v-model数组
      this.userids = [];
      //如果是更新，初始化userids数据，并且只初始化一次
      if(this.form.visitRecordId != null && this.isFirst){
         this.userids = this.form.visitRecordUsers.split(',').map(Number);
         this.isFirst = false;
      }
      //清空表单对应的数据
      this.form.visitRecordUsers = '';
      this.form.visitRecordUserNames = '';
      //undefined是一种类型，不是一个值
      if (v !== undefined && v !== null) {
         getusers({"deptId": v}).then(response => {
           this.users = response.users;
           
         });
         
      }
    },
    
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有拜访记录数据项？').then(() => {
        this.exportLoading = true;
        return exportRecords(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  },
  watch: {
    'form.visitRecordDeptId' : 'onDeptChange'
  }
};
</script>
